package main

import (
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"strings"
	"sync"
	"time"
)

var domains = []string{
	"baidu.com",
	"sina.com.cn",
	"www.baidu.com",
	"www.sina.com.cn",
	"tieba.baidu.com",
	"news.baidu.com",
	"news.sina.com.cn",
}

func main() {
	myTransport := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   15 * time.Second,
			KeepAlive: 15 * time.Second,
			DualStack: true,
		}).DialContext,
		MaxConnsPerHost:       2,
		MaxIdleConns:          10,
		MaxIdleConnsPerHost:   2,
		IdleConnTimeout:       30 * time.Second,
		ResponseHeaderTimeout: 0,
		ExpectContinueTimeout: 1 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
	}
	myClient := http.Client{
		Transport: myTransport,
		Timeout:   20 * time.Second,
	}

	var wg sync.WaitGroup
	for _, domain := range domains {
		wg.Add(1)
		go func(domain string) {
			var logBuf strings.Builder
			var diff time.Duration
			defer func() {
				logBuf.WriteString(fmt.Sprintf("持续时间: %s\n", diff))
				fmt.Println(logBuf.String())
				wg.Done()
			}()
			url := "https://" + domain
			logBuf.WriteString(fmt.Sprintf("发送请求: %s\n", url))
			tStart := time.Now()
			resp, err := myClient.Get(url)
			diff = time.Now().Sub(tStart)
			if err != nil {
				logBuf.WriteString(fmt.Sprintf("request get error: %v\n", err))
				return
			}
			defer resp.Body.Close()
			line := resp.Proto + " " + resp.Status
			logBuf.WriteString(fmt.Sprintf("response: %s\n", line))

			data, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				logBuf.WriteString(fmt.Sprintf("get data error: %v\n", err))
				return
			}
			index1 := strings.Index(string(data), "<title>")
			index2 := strings.Index(string(data), "</title>")
			if index1 > 0 && index2 > 0 {
				logBuf.WriteString(fmt.Sprintf("title: %s\n", string(data)[index1+len("<title>"):index2]))
			}
		}(domain)
	}
	wg.Wait()
	fmt.Println("All Done")
}
